package com.rxkj.fxx.face;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.baidu.idl.face.platform.FaceStatusNewEnum;
import com.baidu.idl.face.platform.model.ImageInfo;
import com.baidu.idl.face.platform.ui.FaceLivenessActivity;
import com.fxx.face.http.http.HttpUtils;
import com.fxx.face.http.inteface.FaceRequestCallback;
import com.fxx.face.http.utils.SharedPreferencesUtil;
import com.rxkj.fxx.face.widget.LoadingBar;
import com.rxkj.fxx.face.widget.TimeoutDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * @ProjectName: FaceRecognition
 * @Package: com.rxkj.fxx.face
 * @ClassName: UpdateFaceActivity
 * @Description:        更新人脸
 * @Author: 付小歆
 * @CreateDate: 2021/12/28 11:35
 */
public class UpdateFaceActivity extends FaceLivenessActivity implements
        TimeoutDialog.OnTimeoutDialogClickListener {

    private TimeoutDialog mTimeoutDialog;

    private String id;

    /**
     * 百度人脸识别token
     */
    private String token = "";

    /**
     * loading弹框
     *
     * @param savedInstanceState
     */
    private LoadingBar loadingBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTitle.setText("人脸更新");
        loadingBar = new LoadingBar(this);

        id = getIntent().getStringExtra("id");
        Log.e("fxx","id="+id);

        //动态获取相机权限
        initPermission();
    }

    private String[] permissions = new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.CAMERA};

    private List<String> mPermissionList = new ArrayList<>();

    private void initPermission() {
        mPermissionList.clear();

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permission);
            }
        }

        //申请权限
        if (mPermissionList.size() > 0) {
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        if (1 == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                    break;
                }
            }
        }
        if (hasPermissionDismiss) {//如果有没有被允许的权限
            Toast.makeText(UpdateFaceActivity.this, "没有相应的权限，无法使用该功能！", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            //权限已经都通过了，可以将程序继续打开了

        }
    }

    @Override
    public void onLivenessCompletion(FaceStatusNewEnum status, String message,
                                     HashMap<String, ImageInfo> base64ImageCropMap,
                                     HashMap<String, ImageInfo> base64ImageSrcMap, int currentLivenessCount) {
        super.onLivenessCompletion(status, message, base64ImageCropMap, base64ImageSrcMap, currentLivenessCount);
        if (status == FaceStatusNewEnum.OK && mIsCompletion) {
            // 获取最优图片
            getBestImage(base64ImageCropMap, base64ImageSrcMap);
        } else if (status == FaceStatusNewEnum.DetectRemindCodeTimeout) {
            if (mViewBg != null) {
                mViewBg.setVisibility(View.VISIBLE);
            }
            showMessageDialog();
        }
    }


    /**
     * 获取最优图片
     *
     * @param imageCropMap 抠图集合
     * @param imageSrcMap  原图集合
     */
    private void getBestImage(HashMap<String, ImageInfo> imageCropMap, HashMap<String, ImageInfo> imageSrcMap) {
        String bmpStr = null;
        // 将抠图集合中的图片按照质量降序排序，最终选取质量最优的一张抠图图片
        if (imageCropMap != null && imageCropMap.size() > 0) {
            List<Map.Entry<String, ImageInfo>> list1 = new ArrayList<>(imageCropMap.entrySet());
            Collections.sort(list1, new Comparator<Map.Entry<String, ImageInfo>>() {

                @Override
                public int compare(Map.Entry<String, ImageInfo> o1,
                                   Map.Entry<String, ImageInfo> o2) {
                    String[] key1 = o1.getKey().split("_");
                    String score1 = key1[2];
                    String[] key2 = o2.getKey().split("_");
                    String score2 = key2[2];
                    // 降序排序
                    return Float.valueOf(score2).compareTo(Float.valueOf(score1));
                }
            });
        }

        // 将原图集合中的图片按照质量降序排序，最终选取质量最优的一张原图图片
        if (imageSrcMap != null && imageSrcMap.size() > 0) {
            List<Map.Entry<String, ImageInfo>> list2 = new ArrayList<>(imageSrcMap.entrySet());
            Collections.sort(list2, new Comparator<Map.Entry<String, ImageInfo>>() {

                @Override
                public int compare(Map.Entry<String, ImageInfo> o1,
                                   Map.Entry<String, ImageInfo> o2) {
                    String[] key1 = o1.getKey().split("_");
                    String score1 = key1[2];
                    String[] key2 = o2.getKey().split("_");
                    String score2 = key2[2];
                    // 降序排序
                    return Float.valueOf(score2).compareTo(Float.valueOf(score1));
                }
            });
            bmpStr = list2.get(0).getValue().getBase64();
        }

        //网络请求
        HttpUtils.updateFace(bmpStr, "groupId", id,
                false,new FaceRequestCallback(){
                    @Override
                    public void onShowDialog() {
                        super.onShowDialog();
                        showLoading("人脸更换中...");
                    }

                    @Override
                    public void onUpdateSuccess(String msg, String faceToken) {
                        super.onUpdateSuccess(msg, faceToken);
                        showToast(msg);
                        SharedPreferencesUtil sp = new SharedPreferencesUtil(UpdateFaceActivity.this);
                        sp.put("token",faceToken);
                        finish();
                    }

                    @Override
                    public void onFail(String error) {
                        super.onFail(error);
                        showToast(error);
                        onPause();
                        onResume();
                    }

                    @Override
                    public void onDismissDialog() {
                        super.onDismissDialog();
                        dissmissLoading();
                    }
                });
    }

    private void showMessageDialog() {
        mTimeoutDialog = new TimeoutDialog(this);
        mTimeoutDialog.setDialogListener(this);
        mTimeoutDialog.setCanceledOnTouchOutside(false);
        mTimeoutDialog.setCancelable(false);
        mTimeoutDialog.show();
        onPause();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void onRecollect() {
        if (mTimeoutDialog != null) {
            mTimeoutDialog.dismiss();
        }
        if (mViewBg != null) {
            mViewBg.setVisibility(View.GONE);
        }
        onResume();
    }

    @Override
    public void onReturn() {
        if (mTimeoutDialog != null) {
            mTimeoutDialog.dismiss();
        }
        finish();
    }

    private void showLoading() {
        if (loadingBar != null)
            loadingBar.show();
    }

    private void showLoading(String hint) {
        if (loadingBar != null)
            loadingBar.canCancellable(false);
        loadingBar.show(hint);
    }

    private void dissmissLoading() {
        if (loadingBar != null && loadingBar.isShowing())
            loadingBar.dissmiss();
    }

    private void showToast(String msg) {
        Toast toast = Toast.makeText(UpdateFaceActivity.this, "",
                Toast.LENGTH_SHORT);
        toast.setText(msg);
        toast.show();
    }
}
